package mysqldb

import (
	"github.com/siddontang/go-mysql/client"
	"github.com/siddontang/go-mysql/mysql"
	"hermes/manager"
	"strconv"
	"strings"
)

func GetMysqlBaseConfig()(uint32,string,uint16,string,string)  {
	mysqlConfg := manager.GetMysqlConfig()
	return mysqlConfg.SlaveId,mysqlConfg.Host,mysqlConfg.Port,mysqlConfg.Username,mysqlConfg.Password
}

func GetMysqlConfig(dbname string)(string,string,string,string)  {
	_,host,port,username,password  := GetMysqlBaseConfig()
	return host+":"+strconv.FormatUint(uint64(port),10),username,password,dbname
}

func GetLastMysqlLogPosByDb() mysql.Position {
	conn, _ := client.Connect(GetMysqlConfig("information_schema"))
	r, _ := conn.Execute("show master status;" )
	var mysqlPos mysql.Position
	for rowIndex := range r.Values {
		fileName, _ := r.GetStringByName(rowIndex, "File")
		pos,_ := r.GetUintByName(rowIndex,"Position")
		mysqlPos = mysql.Position{fileName,uint32(pos)}
	}
	return mysqlPos
}

func GetTableNames(fullTableName string) [][]string {
	kv := strings.Split(fullTableName, ".")
	dbName:=kv[0]
	tableName:=kv[1]
	conn, _ := client.Connect(GetMysqlConfig(dbName))
	r, _ := conn.Execute("desc " + tableName)
	var ls [][]string = make([][]string,2)
	for rowIndex := range r.Values {
		fieldName, _ := r.GetString(rowIndex, 0)
		typeName, _ := r.GetString(rowIndex, 1)
		ls[0] = append(ls[0], fieldName)
		ls[1] = append(ls[1], typeName)
	}
	return ls
}
